#!/usr/bin/env python3
from py2neo import Graph,Node,Relationship,NodeMatcher,RelationshipMatcher

'''
张威  2019-11-28
稍微练习下对neo4j操作的py2neo API
'''
#创建图连接对象
graph = Graph(
            host="127.0.0.1",  # neo4j 搭载服务器的ip地址，ifconfig可获取到
            http_port=7474,  # neo4j 服务器监听的端口号
            user="neo4j",  # 数据库user name，如果没有更改过，应该是neo4j
            password="neo4j")

#创建节点和关系
# b1 = Node("Book",name= "JAVA")
# b2 = Node("Book",name= "neo4j")
# b1b2 = Relationship(b1,"same project",b2)

# b3 = Node("Book",name= 'notebook')
# b4 = Node("Book",name= 'testbook')

# b5 = Node("Book",name= 'my neo4j learning')

#创建
# graph.create(b1b2)
# graph.create(b3)
# graph.create(b4)
'''
属性查找
'''
#查找节点
matcher = NodeMatcher(graph)
finded = matcher.match(name='neo4j').first()
print(finded)
finded2 = matcher.match(name='neo4j')
for n in finded2:
    print(n)

##where 条件查询
print("======="*20)
nodeList = list(matcher.match().where("_.name=~'n.*'")) #以n开头的
for n in nodeList:
    print(n)

##where 条件查询2 ,用原生语句
print("======="*20)
print("条件查询2 ,用原生语句")
r = "MATCH(a:Book) where a.name='neo4j'  return a"
nodeList  = graph.run(r)
for node in nodeList:
    print(node)
    for  i in node:
        print(i)

print("======="*20)
print('模糊全查找,没有查出来')
nodeList2 = matcher.match().where("_.name='*.n.*'")
for  i in nodeList2:
    print(i)

print("======="*20)
print('模糊查找结尾，没有查出来')
nodeList2 = matcher.match().where("_.name='*.k'")
for  i in nodeList2:
    print(i)

print("======="*20)
print('查询排序')
nodeList = matcher.match().where("_.name=~'n.*'").order_by('_.name').limit(2) #以n开头的
for n in nodeList:
    print(n)


'''
关系查找
'''
print("======="*20)
print('关系查找 所有 ----------------')
relMatch = RelationshipMatcher(graph)
relList = relMatch.match()
for i in relList:
    print(i)
print(type(relList))
print("======="*20)
relList2 = list(relMatch.match()) #其实无需放list中也可以遍历的
for i in relList2:
    print(i)

#一般我们不查询所有的关系，数据量太大了，指定关系查找
# 语法：match(nodes=None, r_type=None, **properties)
print("======="*20)
print('指定关系查找')
relist = relMatch.match(r_type='shopping_with')
for  i in relist:
    print(i)

print("======="*20)
# 语法：match.order_by("_.weight", "max(_.a, _.b)")
print('指定关系匹配，排序，限定返回数量 查找')
relist = relMatch.match().order_by().limit(4)
for i in relist:
    print(i)








